#!/bin/bash
rval=()
rsum=0
schar() {
	if [ ! -n "$1" ]; then
		return
	fi
	if [ ! -n "$2" ]; then
		set "$1" 0
	fi
	if [ $2 -ge 0 ]; then
		tmp="${1:$2}"
	else
		tmp="${1: $2}"
	fi
	echo "${tmp:0:1}"
}
mret() {
	loop=0
	rsum="$#"
	for val in "$@"; do
		rval[$loop]="$val"
		let loop=loop+1
	done
}
gret() {
	if [ ! -n "$1" ]; then
		set 0
	fi
	if [[ $1 -ge $rsum || $1 -lt 0 ]]; then
		return
	fi
	echo "${rval[$[$1]]}"
}
cfgtran() {
	res="$1"
	res="${res//'\:'/:}"
	res="${res//'\\'/\\}"
	echo "$res"
}
cfgfmt() {
	res="$1"
	res="${res//'\'/\\\\}"
	res="${res//':'/\\:}"
	echo "$res"
}
sedfmt() {
	nl=$'\n'
	res="$1"
	res="${res//'\'/\\\\}"
	res="${res//' '/\\ }"
	res="${res//$'\n'/\\$nl}"
	unset nl
	echo "$res"
}
cfgdet() {
	line="$(echo "$1" | grep -Fxn "$2:" | cut -d ':' -f1 | sed -n '1p')"
	loop="$line"
	max="$(echo "$1" | sed -n '$=')"
	end=0
	# echo $line $loop $max
	while [ $loop -lt $max ]; do
		let loop=loop+1
		cont="$(echo "$1" | sed -n "${loop}p")"
		if [[ "$(schar "$cont" -1)" == ':' && "$(schar "$cont" -2)" != '\' ]]; then
			mret "$[$line+1]" "$[$loop-1]"
			end=1
			break
		fi
	done
	if [ "$end" != "1" ]; then
		mret "$[$line+1]" "$loop"
	fi
}
cfgread(){
	cfgdet "$1" "$2"
	res="$(echo "$1" | sed -n "$(gret 0),$(gret 1)p")"
	echo "$(cfgtran "$res")"
}
cfgedit() {
	cfgdet "$1" "$2"
	tmp="$(sedfmt "$(cfgfmt "$3")")"
	echo "$tmp"
	res="$(echo "$1" | sed "$(gret 0),$(gret 1)c\\"$'\n'"$tmp"$'\n')"
	# echo "$res"
	unset tmp
}
cfg() {
	if [ ! -n "$3" ]; then
		return
	fi
	if [ "$1" == "read" ]; then
		cfgread "$2" "$3"
	fi
	if [ "$1" == "edit" ]; then
		cfgedit "$2" "$3" "$4"
	fi
}

tp="$1"
file="$2"
shift 2
cfg "$tp" "$(cat "$file")" "$@"
